package com.webserver.controller;

import com.webserver.core.DispatcherServlet;
import com.webserver.entity.Article;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.*;
import java.net.URISyntaxException;

public class ArticleController {
    private static File articleDir;
    private static File root;
    private static File staticDir;

    static {
        try {
            root = new File(DispatcherServlet.class.getClassLoader().getResource(".").toURI());
            staticDir = new File(root, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        articleDir = new File("./articles");
        if (!(articleDir.exists())) {
            articleDir.mkdirs();
        }
    }


    public void writeArticle(HttpServletResponse response, HttpServletRequest request){
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        String articleAuthor = request.getParameter("article");
        System.out.println(title+","+author+","+articleAuthor);
        File file = null;
        if (title==null||author==null||articleAuthor==null){
            file = new File(staticDir,"/myweb/article_fail.html");
            response.setContentFile(file);
            return;
        }


        File articleFile = new File(articleDir,title+".obj");
        try(
                FileOutputStream fos = new FileOutputStream(articleFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                ){
            Article article = new Article(title,author,articleAuthor);
            oos.writeObject(article);

            file = new File(staticDir,"/myweb/article_success.html");
            response.setContentFile(file);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
